import 'dotenv/config'
import express from 'express'
import cors from 'cors'
import helmet from 'helmet'
import morgan from 'morgan'
import { taskRoutes } from './routes/tasks'
import { aiRoutes } from './routes/ai'
import { statsRoutes } from './routes/stats'
import { exportRoutes } from './routes/export'
import { recurringRoutes } from './routes/recurring'
import { authRoutes } from './routes/auth'
import { kanbanRoutes } from './routes/kanban'
import notificationRoutes from './routes/notifications'
import insightsRoutes from './routes/insights'
import pushRoutes from './routes/push'
import chatRoutes from './routes/chat'
import chatEnhancedRoutes from './routes/chatEnhanced'
import chatLangChainRoutes from './routes/chatLangChain'
import { initDatabase } from './database/init'
import { recurringTaskScheduler } from './services/recurringScheduler'

const app = express()
const PORT = process.env.PORT || 5000

// 中间件
app.use(helmet())
app.use(cors())
app.use(morgan('combined'))
app.use(express.json())

// 路由
app.use('/api/auth', authRoutes)
app.use('/api/tasks', taskRoutes)
app.use('/api/ai', aiRoutes)
app.use('/api/stats', statsRoutes)
app.use('/api/export', exportRoutes)
app.use('/api/recurring', recurringRoutes)
app.use('/api/kanban', kanbanRoutes)
app.use('/api/notifications', notificationRoutes)
app.use('/api/insights', insightsRoutes)
app.use('/api/push', pushRoutes)
app.use('/api/chat', chatRoutes)
app.use('/api/chat', chatEnhancedRoutes)
app.use('/api/chat-langchain', chatLangChainRoutes)

// 健康检查
app.get('/health', (req, res) => {
  res.json({ status: 'OK', timestamp: new Date().toISOString() })
})

app.get('/api/health', (req, res) => {
  res.json({ status: 'OK', timestamp: new Date().toISOString() })
})

// 错误处理中间件
app.use((err: Error, req: express.Request, res: express.Response, next: express.NextFunction) => {
  console.error(err.stack)
  res.status(500).json({ error: '服务器内部错误' })
})

// 启动服务器
async function startServer() {
  try {
    // 初始化数据库
    await initDatabase()
    
    // 启动重复任务调度器
    recurringTaskScheduler.startScheduler()
    
    app.listen(PORT, () => {
      console.log(`🚀 AIDE后端服务已启动，端口: ${PORT}`)
      console.log(`📱 API地址: http://localhost:${PORT}/api`)
      console.log(`🔍 健康检查: http://localhost:${PORT}/api/health`)
      console.log(`🔄 重复任务调度器已启动`)
    })
  } catch (error) {
    console.error('启动服务器失败:', error)
    process.exit(1)
  }
}

startServer()
